﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Security.Cryptography;

namespace eLearning.Utility
{
    public partial class EncryptionData
    {
        // - Encrypt password.
        /// <summary>
        /// Encrypt password wih SHA512 method
        /// </summary>
        /// <param name="pstrPwd">Password string to ecrypt</param>
        /// <returns>Encrypted password</returns>
        public static string Encryption(string pstrPwd)
        {
            string strHex = string.Empty;
            // A hash function works on a byte array, so we will create two arrays, 
            // one for our resulting hash and one for the given text.
            byte[] HashValue, MessageBytes = UnicodeEncoding.Default.GetBytes(pstrPwd);
            // Now we create an object that will hash our text:
            SHA512 sha512 = new SHA512Managed();
            // And finally we calculate the hash and convert it to a hexadecimal string. 
            // Which we can store in a database for example
            HashValue = sha512.ComputeHash(MessageBytes);
            foreach (byte b in HashValue)
                strHex += string.Format("{0:x2}", b);
            return strHex;
        }

        /// <summary>
        /// Check hash value
        /// </summary>
        /// <param name="strOriginal">Original string (ex: password entered by user)</param>
        /// <param name="strHash">Hash value (ex: Hashed value from database)</param>
        /// <returns>true if equal, false if failure</returns>
        public static bool CheckHash(string strOriginal, string strHash)
        {
            string strOrigHash = Encryption(strOriginal);
            return (strOrigHash == strHash);
        }
    }
}
